package team.pikachu.pikachuclient.login;

import android.os.AsyncTask;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import team.pikachu.pikachuclient.R;
import team.pikachu.pikachuclient.beans.School;
import team.pikachu.pikachuclient.beans.temp.UserTemp;
import team.pikachu.pikachuclient.utils.Constants;
import team.pikachu.pikachuclient.utils.HttpUtils;
import team.pikachu.pikachuclient.utils.IPConstants;
import team.pikachu.pikachuclient.utils.InternetUtils;
import team.pikachu.pikachuclient.utils.JsonUtils;
import team.pikachu.pikachuclient.utils.LogUtil;

import static team.pikachu.pikachuclient.utils.LogUtil.getSnackbar;

public class RegisteredActivity extends AppCompatActivity {
    private final static String LOGTAG = LogUtil.makeLogTag(RegisteredActivity.class);

    private int role = 1;
    private String username;
    private String password;
    private String checkpass;
    private String nickname;
    private String phone;
    private int university = 0;
    private String college;
    private String collegeNumber;


    @BindView(R.id.username)
    EditText mUsername;
    @BindView(R.id.password)
    EditText mPassword;
    @BindView(R.id.chekPassword)
    EditText mCheckPass;
    @BindView(R.id.nickname)
    EditText mNickname;
    @BindView(R.id.phone)
    EditText mPhone;
    @BindView(R.id.role_group)
    RadioGroup mRole;
    @BindView(R.id.university)
    AutoCompleteTextView mUniversity;
    @BindView(R.id.college)
    EditText mCollege;
    @BindView(R.id.collegeid)
    EditText mCollegeID;

    @BindView(R.id.register_view)
    View mRegisterView;

    @OnClick(R.id.sign_up)
    void onSignUp(){
        username = mUsername.getText().toString().trim();
        password = mPassword.getText().toString();
        checkpass = mCheckPass.getText().toString();
        nickname = mNickname.getText().toString();
        phone = mPhone.getText().toString();

        college = mCollege.getText().toString();
        collegeNumber = mCollegeID.getText().toString();

        attemptSignUp();
    }

    private void attemptSignUp(){
        boolean cancel = false;
        View focusView = null;

        if(TextUtils.isEmpty(username)){
            mUsername.setError("请输入账号");
            cancel = true;
            focusView = mUsername;
        }else if(username.length() < 4){
            mUsername.setError("账号长度太短");
            cancel = true;
            focusView = mUsername;
        }else if(TextUtils.isEmpty(password)){
            mPassword.setError("请输入密码");
            cancel = true;
            focusView = mPassword;
        }else if(password.length() < 4){
            mPassword.setError("密码长度太短");
            cancel = true;
            focusView = mPassword;
        }else if(!checkpass.equals(password)){
            mCheckPass.setError("输入的密码不匹配");
            cancel = true;
            focusView = mCheckPass;
        }else if(TextUtils.isEmpty(nickname)){
            mNickname.setError("请输入您的昵称");
            cancel = true;
            focusView = mNickname;
        }else if(TextUtils.isEmpty(phone)){
            mPhone.setError("请输入您的手机号码");
            cancel = true;
            focusView = mPhone;
        }else if(phone.length() != 11){
            mPhone.setError("您输入的手机号码有误");
            cancel = true;
            focusView = mPhone;
        }

        if (cancel){
            focusView.requestFocus();
        }else{
            UserTemp userTemp = new UserTemp(username,password,nickname,phone,role,university,college,collegeNumber);
            Log.d(LOGTAG,userTemp.toString());
            Gson gson = new Gson();
            String json = gson.toJson(userTemp);

            boolean isOpenNetwork = InternetUtils.isOpenNetwork(RegisteredActivity.this);
            if(isOpenNetwork) {
                SignUpAsy signUpAsy = new SignUpAsy();
                signUpAsy.execute(IPConstants.SIGN_UP,json);
            } else {
                getSnackbar(mRegisterView,getString(R.string.error_no_network)).show();
            }

        }
    }

    /**
     * 表单提交异步
     */
    private class SignUpAsy extends AsyncTask<String,Void,String> {

        @Override
        protected String doInBackground(String... params) {
            return HttpUtils.sendJson(params[0],params[1]);
        }

        @Override
        protected void onPostExecute(String aBoolean) {
            super.onPostExecute(aBoolean);
            if(aBoolean.equals("success")){
                Log.d(LOGTAG,"success");
                Toast.makeText(RegisteredActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
                finish();

            } else if(aBoolean.equals("fail")){
                Log.d(LOGTAG,"fail");
                Toast.makeText(RegisteredActivity.this,"注册失败",Toast.LENGTH_SHORT).show();
                mUsername.setError("该用户名已被使用");
                mUsername.requestFocus();
            } else if(aBoolean.equals("notFound")){
                Toast.makeText(RegisteredActivity.this,"注册失败",Toast.LENGTH_SHORT).show();
                mUniversity.setError("数据库中没有您的学校信息");
                mUniversity.requestFocus();
            }
        }
    }

    private InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source.equals(" "))
                return "";
            else
                return null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registered);
        ButterKnife.bind(this);

        mRole.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId){
                    case R.id.teacher_radio:
                        role = Constants.ROLE_TEACHER;
                        break;
                    case R.id.student_radio:
                        role = Constants.ROLE_STUDENT;
                        break;
                }
            }
        });

        mUsername.setFilters(new InputFilter[]{filter});
        mPassword.setFilters(new InputFilter[]{filter});
        mCheckPass.setFilters(new InputFilter[]{filter});

        SchoolAsy schoolAsy = new SchoolAsy();
        schoolAsy.execute(IPConstants.GET_SCHOOLS);

        mUniversity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                School school = (School) parent.getItemAtPosition(position);
                String name = school.getName();
                mUniversity.setText(name);
                mUniversity.setSelection(name.length());
                university = school.getId();
            }
        });

    }

    /**
     * 学校名自动补全
     * 适配器适配学校名字List
     *
     */
    private class SchoolAsy extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... params) {
            return HttpUtils.sendPostMethod(params[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            Log.d(LOGTAG,s);
            if (!s.equals(getString(R.string.timeout)) && !s.equals(getString(R.string.request_failed))) {

                School[] schools = JsonUtils.readValue(s, School[].class);

                assert schools != null;
                for (School school : schools) {
                    Log.i(LOGTAG, school.toString());
                }

                List<School> schoolList = Arrays.asList(schools);
                SchoolAdapter arrayAdapter = new SchoolAdapter(RegisteredActivity.this, android.R.layout.simple_list_item_1, schoolList);
                arrayAdapter.setOnCompleteListener(new SchoolAdapter.CompleteListener() {
                    @Override
                    public void onComplete(School school) {
                        university = school.getId();
                    }
                });
                mUniversity.setAdapter(arrayAdapter);
            }

        }
    }
}
